import axios from 'axios';
import EventBus from './event';

export type AxiosRes<T = ResData> = {
  config: object;
  data: T;
  headers: any;
  request: any;
  status: number;
  statusText: string;
};
export type ResData<T = any> = {
  code: number;
  msg: string;
  data: T;
};
export type AxiosResData<T = any> = AxiosRes<ResData<T>>;

// 可以写中间件
const instance = axios.create({
  // 特别重要
  validateStatus: function (status) {
    return status < 500; // 处理状态码小于500的情况
  },
});

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.code === 401) {
        EventBus.emit('global_not_login', response.data.msg);
      }
      if (response.data.code === -1) {
        EventBus.emit('global_error_tips', response.data.msg);
        console.log('response.data.msg', response.data.msg);
      }
    } else if (response.status === 403) {
      EventBus.emit('global_error_auth', '没有权限,不能访问');
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default instance;
